package com.duoduo.admin.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.duoduo.common.core.constant.CacheConstants;
import com.duoduo.common.core.constant.enums.DictTypeEnum;
import com.duoduo.common.core.exception.ErrorCode;
import com.duoduo.common.core.util.R;
import com.duoduo.common.jpa.service.CommonService;
import com.duoduo.admin.api.dto.SysPublicParamDTO;
import com.duoduo.admin.entity.SysPublicParam;
import com.duoduo.admin.repository.SysPublicParamRepository;

import jakarta.persistence.criteria.Predicate;

@Service
public class SysPublicParamService extends CommonService<SysPublicParamDTO, SysPublicParam, Long>{

	@Autowired
	private SysPublicParamRepository sysPublicParamRepository;

	@Override
	public Specification<SysPublicParam> getWhere(final SysPublicParamDTO request) {
		return (root, query, cb) -> {
			final List<Predicate> predicate = new ArrayList<Predicate>();
			if(request.getId()!=null) {
				predicate.add(cb.equal(root.get("id"), request.getId()));	
			}		
			
			final Predicate[] pre = new Predicate[predicate.size()];
			return query.where(predicate.toArray(pre)).getRestriction();
		};
	}
	
	@Cacheable(value = CacheConstants.PARAMS_DETAILS, key = "#publicKey", unless = "#result == null ")
	public String getSysPublicParamKeyToValue(String publicKey) {
		SysPublicParam sysPublicParam = sysPublicParamRepository.findByPublicKey(publicKey).orElseThrow();
		if (sysPublicParam != null) {
			return sysPublicParam.getPublicValue();
		}
		return null;
	}
	/**
	 * 更新参数
	 * @param sysPublicParam
	 * @return
	 */
	@CacheEvict(value = CacheConstants.PARAMS_DETAILS, key = "#sysPublicParam.publicKey")
	public R<Void> updateParam(SysPublicParam sysPublicParam) {
		SysPublicParam param = sysPublicParamRepository.findById(sysPublicParam.getId()).orElseThrow();
		// 系统内置
		if (DictTypeEnum.SYSTEM.getType().equals(param.getSystemFlag())) {
			return R.failed(ErrorCode.PUBLICPARAM_ERROR);
		}
		sysPublicParamRepository.save(sysPublicParam);
		return R.ok();
	}

	/**
	 * 删除参数
	 * @param publicId
	 * @return 
	 * @return
	 */
	@CacheEvict(value = CacheConstants.PARAMS_DETAILS, allEntries = true)
	public R<Void> removeParam(Long publicId) {
		SysPublicParam sysPublicParam = sysPublicParamRepository.findById(publicId).orElseThrow();
		if (DictTypeEnum.SYSTEM.getType().equals(sysPublicParam.getSystemFlag())) {
			return R.failed(ErrorCode.PUBLICPARAM_ERROR);
		}
		// 系统内置
		sysPublicParamRepository.delete(sysPublicParam);
		return R.ok();
	}

	/**
	 * 同步缓存
	 * @return R
	 */
	@CacheEvict(value = CacheConstants.PARAMS_DETAILS, allEntries = true)
	public R syncParamCache() {
		return R.ok();
	}

}
